#!.venv/bin/python3

import sys
import os
import json
import requests
import bs4
from rich import print
from rich.panel import Panel
from rich.prompt import Prompt

TMP = f"{sys.path[0]}/tmp"
if not os.path.exists(TMP):
    os.makedirs(TMP)

DATABASE = f"{TMP}/database.json"
try:
    with open(DATABASE) as f:
        database: dict = json.load(f)
except FileNotFoundError:
    database = {}

CONFIG = f"{TMP}/config.json"
try:
    with open(CONFIG) as f:
        config: dict = json.load(f)
except FileNotFoundError:
    config = {}


def fetch(url: str):
    if not database.get(url):
        # 数据库中不存在则进行拉取
        resp = requests.get(url)
        assert resp.ok
        soup = bs4.BeautifulSoup(resp.text, "html.parser")
        tables = soup.select("table")
        assert len(tables) == 1
        database[url] = [a.text for a in tables[0].select("a")]
        with open(DATABASE, "w") as f:
            json.dump(database, f)
    return database[url]


def save_config():
    with open(CONFIG, "w") as f:
        json.dump(config, f)


def echo_item(list_: list, value, default=None):
    return value if value in list_ else default


def put(path: list[str], prompt, default=None, choices=None):
    key = path.pop()
    current = config
    for name in path:
        current = current.setdefault(name, {})
    current[key] = Prompt.ask(
        prompt, default=current.get(key) or default, choices=choices
    )
    return current[key]


def select_router():
    print(Panel("选择路由器版本"))
    versions_url = "https://downloads.openwrt.org/releases/"
    put(["version"], "选择Openwrt版本", "21.02.3", fetch(versions_url))
    architectures_url = f"{versions_url}{config['version']}/targets/"
    architectures = fetch(architectures_url)
    put(
        ["architecture"],
        "选择CPU架构",
        echo_item(architectures, "ramips"),
        architectures,
    )
    chips_url = f"{architectures_url}{config['architecture']}"
    chips = fetch(chips_url)
    put(
        ["chip"],
        "选择CPU芯片",
        echo_item(chips, "mt7621"),
        chips,
    )
    # TODO 列出可选择列表
    put(["profile"], "选择路由器【在imagebuilder中用make info命令列出所有选项】", "d-team_newifi-d2")
    save_config()


def configure_global():
    print(Panel("配置全局变量"))
    # 密码
    put(["password"], "登录密码")
    put(["wifi", "password"], "wifi密码")
    put(["ssh", "public_key"], "ssh登录公钥")
    # 邮箱
    put(["email"], "邮箱", "13927553153@163.com")
    # 根域名
    put(["domain"], "根域名", "idnewnil.top")
    # 主机
    put(["home"], "路由器主机名【和根域名一同生成子域名】", "home")
    config["domain.home"] = f"{config['home']}.{config['domain']}"
    config["domain.@home"] = f"{config['home']}@{config['domain']}"
    # Cloudflare Global API Key
    put(["cf_key"], "Cloudflare Global API Key")
    save_config()


def configure_wan():
    print(Panel("配置上网"))
    protocal = put(["wan", "protocal"], "选择wan的协议", "dhcp", ["dhcp", "pppoe"])
    if protocal == "pppoe":
        put(["wan", "username"], "pppoe账号")
        put(["wan", "password"], "pppoe密码")
    save_config()


def configure_frpc():
    print(Panel("配置frpc"))
    put(["frpc", "server_addr"], "服务器", f"frps.{config.get('domain')}")
    put(["frpc", "token"], "密令")
    save_config()


select_router()
configure_global()
configure_wan()
configure_frpc()
